1. package
npm install react-autosuggest
import { useState } from 'react';
import Autosuggest from 'react-autosuggest';
// Mock data for item suggestions (replace this with your own data)
const itemSuggestions = [
{ name: 'Item 1', price: 10 },
{ name: 'Item 2', price: 20 },
// Add more items as needed
];
const BillingForm = () => {
const [items, setItems] = useState([{ itemName: '', quantity: 0, price: 0 }]);
const [suggestions, setSuggestions] = useState([]);
const getSuggestions = (value) => {
const inputValue = value.trim().toLowerCase();
const inputLength = inputValue.length;
return inputLength === 0
? []
: itemSuggestions.filter(
(item) =>
item.name.toLowerCase().slice(0, inputLength) === inputValue
);
};
const onSuggestionsFetchRequested = ({ value }) => {
setSuggestions(getSuggestions(value));
};
const onSuggestionsClearRequested = () => {
setSuggestions([]);
};
const onSuggestionSelected = (event, { suggestion }) => {
// Add the selected item to the items list
const newItems = [...items];
newItems[newItems.length - 1].itemName = suggestion.name;
newItems[newItems.length - 1].price = suggestion.price;
setItems(newItems);
};
const handleItemChange = (index, event) => {
const { name, value } = event.target;
const newItems = [...items];
newItems[index][name] = value;
setItems(newItems);
};
const addNewItem = () => {
setItems([...items, { itemName: '', quantity: 0, price: 0 }]);
};
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission with items data
console.log(items);
};
const inputProps = {
placeholder: 'Item Name',
value: items[items.length - 1].itemName,
onChange: (event, { newValue }) => {
const newItems = [...items];
newItems[newItems.length - 1].itemName = newValue;
setItems(newItems);
},
};
return (
);
};
export default BillingForm;